<?php
class template {
	protected $tpl_dir;
	protected $vars = array();//Template variable storage
	protected $file;//Template filename
	
	public function __construct($dir = "./") {
		global $tpl_common_vars;
		if(!empty($tpl_common_vars)) {
			foreach ($tpl_common_vars as $key => &$val) {
				$this->vars[$key] = $val;
			}
		}

		if (!is_dir($dir))
			die("<p><b>Tpl error: ".$dir."</b> does not exist!<p>");
		$this->tpl_dir = $dir;
	}

	//Create/change template variable
	public function setVar($name, $value) {
		$this->vars[$name] = $value;
	}

	//Creates/changes multiple template variables
	public function setVars($array) {
		//$this->vars = array_merge($this->vars, $array);
		foreach ($array as $key => $val) {
			$this->vars[$key] = $val;
		}
	}

	public function setBlockVars($name, $array) {
		$this->vars[$name][] = $array;
	}


	public function unsetVar($name) {
		unset($this->vars[$name]);
	}
	public function clearVars() {
		$this->vars = array();
	}

	public function display($file) {
		$this->file = $this->tpl_dir . $file;
		unset($file);
		
		if (!file_exists($this->file))
			die("<p><b>Tpl error: ".$this->file."</b> does not exist!<p>");
					
		//extract($this->vars, EXTR_OVERWRITE); // create vars from data array
		// sukuria kintamųjų vardus, o jų turinys lieka ten pat kur buvo pries tai.
		foreach ($this->vars as $key => &$val) {
			$$key = $val;
		}
		
		ob_start(); // start output buffering:
		require $this->file; // parse the file.
		$r = ob_get_contents(); // get parsed text
		ob_end_clean(); // quietly end output buffering
		/*
		Kitas variantas, viena eilute:
		$r = ob_get_clean();
		*/
		return $r;
	}
}
?>
